package org.dark;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.util.AttributeKey;

import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * @author xiaozefeng
 * @date 2018/11/30 2:50 PM
 */
public class NettyClient {

    private static final int MAX_RETRY_COUNT = 5;

    public static void main(String[] args) throws InterruptedException {
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();

        Bootstrap bootstrap = new Bootstrap();
        bootstrap
                .group(workerGroup) // 指定线程模型
                .channel(NioSocketChannel.class) // 指定io模型
                .attr(AttributeKey.newInstance("clientName"), "nettyClient") // 绑定自定义属性到channel
                // 设置TCP底层属性
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000)
                .option(ChannelOption.SO_KEEPALIVE, true)
                .option(ChannelOption.TCP_NODELAY, true)
                //  IO 处理
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {

                    }
                });

        // 建立连接
        connect(bootstrap, "127.0.0.1", 8000, MAX_RETRY_COUNT);
    }

    private static void connect(Bootstrap bootstrap, String host, int port, int retry) {
        bootstrap.connect(host, port).addListener(future -> {
            if (future.isSuccess()) {
                System.out.println("connected successful");
            } else if (retry == 0) {
                System.out.println("retry has been used, cancel the connection");
            } else {
                // 第几次连接
                int order = (MAX_RETRY_COUNT - retry) + 1;
                int delay = 1 << order;
                System.out.println(new Date() + ": connected failed. 第" + order + "重连");
                bootstrap.config().group().schedule(() -> connect(bootstrap, host, port, retry - 1), delay, TimeUnit.SECONDS);
            }
        });
    }

}
